import json

from django.contrib.auth import login

from django.http import JsonResponse

# Create your views here.
from django.views import View

from apps.cart.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User
from meiduo import settings


# 返回 扫描的页面地址
class QQLoginURLView(View):

    def get(self, request):
        # 1使用QQloginTool生成跳转链接
        # 1.1导入
        from QQLoginTool.QQtool import OAuthQQ
        # 1.2初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="xxx")
        # 1.3 获取QQ登录扫码页面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()
        # 2返回响应

        return JsonResponse({"code": 0, "login_url": login_url})


class OauthView(View):
    # /oauth_callback/?code=fjdsskfklsdjl
    def get(self, request):
        # 1获取code
        code = request.GET.get("code")
        # 省略了code如果不存在 返回错误
        print(code)
        # 2根据code获取token
        # 2.1导入
        from QQLoginTool.QQtool import OAuthQQ
        # 2.2初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="xxx")
        # try:这里的获取 是要联网和腾讯通信的 正确的写法要捕获异常
        access_token = oauth.get_access_token(code)
        print(access_token)
        # 3根据token获取openid
        openid = oauth.get_open_id(access_token)
        print("openid--原", openid)
        # except Exception as e:
        #     return JsonResponse({"code": 400, "access_token": openid})

        # 4 根据openid去数据库查询OAuthQQUser 帐号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print(e)
            # 4.1如果不存在   捕获异常   走没有绑定的逻辑 去绑定页面
            # 前段分析后 返回openid  key叫做access_token

            # 对openid加密
            openid = generate_access_token(openid)
            print("openid--加密后", openid)
            return JsonResponse({"code": 400, "access_token": openid})
        else:
            # 4.2如果存在  正常返回数据  做登录状态保持
            # session
            login(request, qquser.user)
            # cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("username", qquser.user.username)
            # 合并cookie购物车到redis
            response = merge_cart_cookie_to_redis(request, qquser.user, response)

            return response

    def post(self, request):
        # 1 接收请求
        body = request.body
        data_dict = json.loads(body)

        # 2 获取请求参数  手机号 密码 短信验证码openid
        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")
        print("openid---", openid)
        # 对openid解密获取原数据
        openid = check_access_token(openid)
        print(openid)

        # 验证参数（省略）

        # 3 根据手机号  查询是否已经注册
        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            print(e)
            # 5 没有注册  创建一个user对象 绑定  用户和openid
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 4 已经注册  密码验证  密码正确 直接绑定  用户和openid
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "账号或者密码错误"})

        try:
            # 绑定user和openid
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "账号已经绑定 无法添加"})

        # 6 状态保持
        login(request, user)
        response = JsonResponse({"code": 0, "errmsg": "ok"})
        response.set_cookie("username", user.username)
        # 合并cookie购物车到redis
        response = merge_cart_cookie_to_redis(request, user, response)

        # 7 返回响应
        return response
